import echarts from 'echarts';
import fecha from '@/utils/date';

export default {
  chartIns: null,
  chartData: [],
  filter: {
    suffixTitle: '',
    devName: '',
    startDate: new Date(),
    endDate: ''
  },
  initChart (el, data, filter) {
    if (!this.chartIns) {
      this.chartIns = echarts.init(el);
    }
    this.chartData = data;
    this.filter = filter;
    this.setOption();
  },
  resizeChart () {
    this.chartIns && this.chartIns.resize();
  },
  disposeChart () {
    if (this.chartIns) {
      this.chartIns.dispose();
      this.chartIns = null;
    }
  },
  setOption () {
    const _self = this;

    if (this.chartIns && this.chartData) {
      const series = [];
      const legend = [];
      this.chartData.forEach((entry, index) => {
        series.push({
          type: 'line',
          showSymbol: false,
          name: entry.name,
          data: entry.dataList,
          markPoint: {
            data: [
              { type: 'max', name: '最大值' },
              { type: 'min', name: '最小值' }
            ]
          }
        });
        legend.push(entry.name);
      });
      // 缩放的开始时间，取结束时间的零点
      const endDate = this.filter.endDate || this.filter.startDate;
      const startValue = (new Date(fecha.format(endDate, 'yyyy'), fecha.format(endDate, 'MM') - 1, fecha.format(endDate, 'dd'))).getTime();

      let subtitle = fecha.format(this.filter.startDate, 'yyyy-MM-dd');
      if (this.filter.endDate && this.filter.endDate.getTime() !== this.filter.startDate.getTime()) {
        subtitle += ' 至 ' + fecha.format(this.filter.endDate, 'yyyy-MM-dd');
      }

      this.chartIns.clear();
      this.chartIns.resize();
      this.chartIns.setOption({
        title: {
          left: 10,
          text: this.filter.devName + ' ' + this.filter.suffixTitle,
          textStyle: {
            fontSize: 14
          },
          subtext: subtitle,
          itemGap: 5
        },
        grid: {
          right: '3.2%'
        },
        legend: {
          width: '94%',
          left: 'center', // 12,
          right: 6,
          top: 30,
          type: 'scroll',
          data: legend
        },
        toolbox: {
          right: 18,
          itemSize: 12,
          feature: {
            dataZoom: {
              yAxisIndex: 'none'
            },
            restore: {},
            saveAsImage: {}
          }
        },
        tooltip: {
          trigger: 'axis',
          formatter: function (params) {
            let showString = fecha.format(params[0].axisValue, 'yyyy年MM月dd日 HH:mm') + '<br />';
            params.forEach((item, index) => {
              showString += '<span style="color: ' + item.color + ';font-size: 20px;">●</span> ';
              showString += item.seriesName + '：' + item.value[1] + ' ' + (_self.chartData[item.seriesIndex].unit || '') + '<br />';
            });
            return showString;
          },
          axisPointer: {
            animation: false
          }
        },
        dataZoom: [{
          startValue: startValue
        }, {
          type: 'inside'
        }],
        xAxis: {
          type: 'time',
          axisLabel: {
            formatter: function (value, index) {
              let label = fecha.format(value, 'HH:mm');
              if (label === '00:00') {
                label = fecha.format(value, 'MM-dd');
              }
              return label;
            }
          }
        },
        yAxis: {
          type: 'value',
          boundaryGap: [0, '100%'],
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: series
      });
    }
  },
  // 调压分析曲线图
  loadTiaoyaChart (el, data = [], filter = {}) {
    const series = [];
    const legend = [];
    data.forEach((entry, index) => {
      const seriesItem = {
        type: 'line',
        showSymbol: false,
        name: entry.name,
        data: entry.dataList
      };
      if (filter.max && filter.min) {
        seriesItem.markLine = {
          symbol: '',
          label: {
            show: false,
            position: 'middle',
            formatter: '{b}：{c}'
          },
          emphasis: {
            label: {
              show: true
            }
          },
          data: [
            {
              name: '上限',
              yAxis: filter.max
            },
            {
              name: '下限',
              yAxis: filter.min
            }
          ]
        };
      }
      if (filter.step) {
        seriesItem.step = filter.step;
        seriesItem.data.forEach(item => {
          item[1] += 2 * index;
        });
      }
      if (filter.end && seriesItem.data.length) {
        seriesItem.data.push([filter.end, seriesItem.data[seriesItem.data.length - 1][1]]);
      }
      series.push(seriesItem);
      legend.push(entry.name);
    });
    let days = 1;
    let xInterval = null;
    if (series.length) {
      if (filter.start && filter.end) {
        days = Math.ceil((filter.end - filter.start) / (24 * 3600 * 1000));
        xInterval = (filter.end - filter.start) / 8;
      } else {
        days = Math.ceil(series[0].data.length / 300);
        xInterval = days * 24 * 3600 * 1000 / 8;
      }
    }
    const tiaoyaChart = echarts.init(el);
    tiaoyaChart.setOption({
      title: {
        left: 'center',
        top: -5,
        text: filter.title,
        textStyle: {
          fontSize: 12
        }
      },
      grid: {
        right: '3.2%',
        top: 20,
        bottom: 20
      },
      legend: {
        left: 'center',
        top: 24,
        data: legend
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          let showString = fecha.format(params[0].axisValue, 'yyyy年MM月dd日 HH:mm') + '<br />';
          params.forEach((item, index) => {
            let value = item.value[1];
            if (filter.step) {
              value = item.value[1] % 2 === 0 ? '切出' : '投入';
            }
            showString += '<span style="color: ' + item.color + ';font-size: 20px;">●</span> ';
            showString += item.seriesName + '：' + value + ' ' + (filter.unit || '') + '<br />';
          });
          return showString;
        },
        axisPointer: {
          animation: false
        }
      },
      xAxis: {
        type: 'time',
        interval: xInterval,
        axisLabel: {
          formatter: function (value, index) {
            let label = fecha.format(value, 'MM-dd HH:mm');
            if (days < 3 || days === 4) {
              label = fecha.format(value, 'HH:mm');
            }
            if (index === 0 || label === '00:00') {
              label = fecha.format(value, 'MM-dd');
            }
            return label;
          }
        },
        min: filter.start || 'dataMin',
        max: filter.end || 'dataMax'
      },
      yAxis: {
        name: filter.unit ? ('单位：' + filter.unit) : '',
        nameGap: 8,
        type: 'value',
        boundaryGap: [0, '100%'],
        splitLine: {
          lineStyle: {
            type: 'dashed',
            opacity: 0.3
          }
        },
        axisLabel: {
          formatter: (value) => {
            if (filter.step) {
              return value === 6 ? '' : (value % 2 === 0 ? '切' : '投');
            } else {
              return value;
            }
          }
        },
        max: filter.max ? filter.max + 1 : 6,
        min: filter.min ? filter.min - 1.5 : 0
      },
      series: series
    });
    return tiaoyaChart;
  }
};
